package teamCservlets;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;


public class LoginLogoutServlet extends HttpServlet {
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	
		// Determine which button was clicked and service the request.
		// If neither the login or logout button was clicked, send the user
		// to the login page.
		if (request.getParameter("loginButton") != null) {
			loginUser(request, response);
		} else if (request.getParameter("logoutButton") != null) {
			logoutUser(request, response);
		} else {
			response.sendRedirect("login.jsp");
		}
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws IOException, ServletException {
		doPost(request, response);
	}

	/**
	 * Service the "login" request by finding the user with the specified email
	 * address.  If found, the defectlist page is displayed.  If not found, the
	 * login page is redisplayed with an error message.  In either case, a
	 * PersonBean object is stored in the session, and its validity is determined
	 * by examining its ID (-1 = invalid).
	 */
	private void loginUser(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {

		PersonBean	authUser = null;
		String 		nextPage = null;
		DatabaseInterfacePerson db = new DatabaseInterfacePerson();
		
		// Get the email address from the form and query the database for
		// a person with that address.
		String loginEmail = request.getParameter("emailAddr");
		if ((loginEmail != null) && (!loginEmail.trim().equals(""))) {
			authUser = db.getPerson(loginEmail);
		} 

		// If there wasn't any email address field entered in the form,
		// or no match was found in the database, create an "invalid" 
		// person object via the no-arg constructor.  Invalidity is indicated 
		// the person's ID = -1.
		if (authUser == null) {
			authUser = new PersonBean();
		}

		// If the person object is invalid, create an error message and set the next
		// page back to the login page.  (Not using sendRedirect here because in
		// that case the error message would not be displayed.)
		if (authUser.getId() == -1) {
			request.setAttribute("errorMessage", "Invalid email address");
			nextPage = "login.jsp";
		} else {
			// If a database match was found, the next page to be displayed 
			// is the defect list.  Forward the request to the DefectServlet.
			nextPage = "displayhomepage";
			request.setAttribute("defectlistmessage", "");
		}
		
		// Add the person object to the session as "user", whether or not it's valid, so that
		// each jsp page & servlet can determine who (if anybody) is logged in
		HttpSession session = request.getSession();
		session.setAttribute("user", authUser);
		
		// Remove any session attributes that might be leftover from a previous session.
		session.removeAttribute("currentDefectId");
		session.removeAttribute("applicationList");
		session.removeAttribute("personList");
		session.removeAttribute("newDefect");
		session.removeAttribute("currentDefect");

		// Set up the JSP forward, and forward the request
		RequestDispatcher dispatcher = request.getRequestDispatcher(nextPage);
		dispatcher.forward(request, response);
		
		return;
	}

	/**
	 * Service the "logout" request by clearing out the logged-in user's identity
	 * and redisplaying the login page.
	 */
	private void logoutUser(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {

		// Get the session object.  Create a new (invalid) person object, and add it
		// to the session as "user", replacing what was there previously.
		HttpSession session = request.getSession();
		PersonBean	authUser = new PersonBean();
		session.setAttribute("user", authUser);
		
		// The login page will be redisplayed, with a message
		request.setAttribute("errorMessage", "You have been logged out.");	
		String nextPage = "login.jsp";	
		
		// Set up the JSP forward, and forward the request. (Not using sendRedirect 
		// here because in that case the message would not be displayed.)
		RequestDispatcher dispatcher = request.getRequestDispatcher(nextPage);
		dispatcher.forward(request, response);
		
		return;
	}
}
